#include "packetsender.hpp"
#include <stdint.h>
#include <string.h>
#include <algorithm>
typedef struct rftap_hdr {
	int32_t magic;  // "RFta"
	uint16_t len32;  // sizeof(rftap_hdr) / sizeof(le32)
	uint16_t flags;  // bitfield indicating presence of parameters
	int32_t data[1];
}rftap;



packetsender::packetsender(std::string ip_addr)
{
#if defined(_WIN32)
	WSADATA wsaData;
	WSAStartup(0x0202, &wsaData);
#endif

	s = socket(AF_INET, SOCK_DGRAM, 0);
	addrSrv.sin_family = AF_INET;
	addrSrv.sin_port = htons(52001);
	addrSrv.sin_addr.s_addr = inet_addr(ip_addr.c_str());
}

packetsender::~packetsender()
{
#if defined(_WIN32)
	closesocket(s);
	WSACleanup();
#else
	close(s);
#endif
}

void packetsender::send(lell_packet pkt)
{
	rftap _rftap;
	memset(buffer, 0, sizeof(buffer));
	size_t size=0;
	_rftap.magic = 0x61744652UL;
	_rftap.len32 = sizeof(rftap) / sizeof(int32_t);
	_rftap.flags = 0x01;
	_rftap.data[0] = 256;//DLT_BLUETOOTH_LE_LL_WITH_PHDR

	memcpy(buffer, &_rftap, sizeof(_rftap));
	size += sizeof(_rftap);

	pcap_bluetooth_le_ll_header blepkt;
	blepkt.rf_channel = pkt.channel_k;
	blepkt.ref_access_address = (pkt.channel_idx<37)?0 : 0x8e89bed6;
	blepkt.noise_power=INT8_MIN;
	blepkt.access_address_offenses = pkt.access_address_offenses;
	blepkt.flags = LE_DEWHITENED | LE_AA_OFFENSES_VALID | LE_SIGPOWER_VALID | LE_NOISEPOWER_VALID;

	memcpy(&blepkt.le_packet[0], &pkt.symbols[0], std::min<size_t>(LE_MAX_PAYLOAD,pkt.length+4+2+3));

	memcpy(buffer+ size, &blepkt, sizeof(blepkt));
	size += sizeof(blepkt)-LE_MAX_PAYLOAD+ std::min<size_t>(LE_MAX_PAYLOAD,pkt.length+4+3);// AA + header + CRC

	sendto(s, buffer, size, 0, (struct sockaddr *)&addrSrv, sizeof(struct sockaddr_in));

}
